<?
/** 
 *  Classe per l'autenticazione degli utenti tramite username e password
 *  oppure Cookie sul PC del client, è possibile impostare una pagina di approdo
 *  dinamica.
 *  
 *  
 *  $ua = new UserAuth($db);
 *  if($ua->login())
 *  {
 *  	...
 *  }else
 *  {
 *  	header("location:index.php?mod=login&dest=$_REQUEST[mod]");
 * 		exit();
 *  }
 *  
 */
class UserAuth
{
	var $db;
	var $userIP;

	var $username;
	var $id_user;
	var $usercookie;
	var $last_login;
	
	var $permessi;

	var $debug;

	function UserAuth(&$db)
	{
		$this->db =& $db;
		$this->userIP = UserAuth::getUserIP();
		$this->usercookie = $_COOKIE['UA_usercookie'];	
		$this->permessi = array();	
	}
	
	/**
	 * Esegue il login dell'utente con username e password oppure accede usando il cookie.
	 * Se l'utente è già loggato ritorna true senza ulteriori verifiche 
	 *
	 * @return boolean
	 */
	function login($id_negozio)
	{
		$logusername = $_REQUEST[username];
		$logpassword = md5($_REQUEST[password]);		
		$this->debug[] = "Richiesto login $logusername $logpassword";
		
		if($this->is_logged())
		{
			$this->debug[] = "Già loggato ID:$this->id_user";
			if($_REQUEST[dest] && $_REQUEST[mod]=="login")$_REQUEST[mod] = $_REQUEST[dest];
		
			return true;
		}
		elseif($logusername && $logpassword) 
		{
			$query = "SELECT * FROM users WHERE username=\"$logusername\" AND password=\"$logpassword\" ";
			$rs = $this->db->query($query);
			if($rw = mysql_fetch_assoc($rs))
			{
				$this->username = $_SESSION[UA_username] = $rw[username];
				$this->id_user = $_SESSION[UA_id_user] = $rw[id];
				$this->last_login = $_SESSION[UA_last_login] = $rw[last_login];	
				// RECUPERO PERMESSI
				$query = "SELECT * FROM users_permessi WHERE id_user=\"$rw[id]\" AND id_negozio='$id_negozio' ";
				$rsp = $this->db->query($query);
				if($rwp = mysql_fetch_assoc($rsp))
				{
					foreach($rwp as $nome=>$valore)$this->permessi[$nome]=$valore;
				}
				$_SESSION[UA_permessi] = $this->permessi;
				
				$this->debug[] = "Login eseguito ID:$this->id_user";
				$this->log_activity($logusername);	
				$this->writeLog("OK pwd\t".$logusername);			
				return true;		
			}
			else 
			{
				$this->logout();
				$this->writeLog("ERR pwd\t".$logusername." ".$_REQUEST[password]);
				return false;
			}
		}
		elseif($this->usercookie)
		{
			$query = "SELECT * FROM users WHERE cookiepwd=\"".md5($this->usercookie)."\" ";
			$rs = $this->db->query($query);
			if($rw = mysql_fetch_assoc($rs))
			{			
				$this->username = $_SESSION[UA_username] = $rw[username];
				$this->id_user = $_SESSION[UA_id_user] = $rw[id];	
				$this->last_login = $_SESSION[UA_last_login] = $rw[last_login];	
				// RECUPERO PERMESSI
				$query = "SELECT * FROM users_permessi WHERE id_user=\"$rw[id]\" AND id_negozio=\"$id_negozio\" ";
				$rsp = $this->db->query($query);
				if($rwp = mysql_fetch_assoc($rsp))
				{
					foreach($rwp as $nome=>$valore)$this->permessi[$nome][$valore];
				}
				$_SESSION[UA_permessi] = $this->permessi;
							
				$this->debug[] = "Login eseguito da cookie ID:$this->id_user";		
				$this->log_activity($logusername);	
				$this->writeLog("OK cookie\t".$logusername);			
				return true;		
			}else 
			{
				$this->logout();
				$this->writeLog("ERR cookie\t".$logusername." ".$_REQUEST[password]);
				return false;
			}
		}
		return -1;
	}
	
	/**
	 * Esegue il logout, annulla le variabili di sessione e cancella eventualmente il cookie ricordami
	 *
	 * @return bool
	 */
	function logout()
	{
		unset($_SESSION[UA_id_user]);
		unset($_SESSION[UA_username]);
		unset($_SESSION[UA_last_login]);
		unset($_SESSION[UA_permessi]);
		unset($this->username);
		unset($this->id_user);
		setcookie("UA_usercookie", "", time()-60);
		return true;
	}
	
	/**
	 * Controlla se l'utente è loggato
	 *
	 * @return bool
	 */
	function is_logged()
	{
		if($_SESSION[UA_id_user]>0) 
		{
			$this->username 	= $_SESSION[UA_username];
			$this->id_user 		= $_SESSION[UA_id_user];
			$this->last_login 	= $_SESSION[UA_last_login];
			$this->permessi 	= $_SESSION[UA_permessi];
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	/**
	 * Scrive data di accesso nel DB e genera se richiesto il cookie UA_usercookie per ricordare l'utente ai prossimi accessi
	 *
	 * @param string $logusername
	 */
	private function log_activity($logusername)
	{

		if($_REQUEST[dest] && $_REQUEST[mod]=="login")$_REQUEST[mod] = $_REQUEST[dest];
		if($_REQUEST[rememberme]>0)
		{
			$cookie_val = md5(time()+$logusername+rand());
			setcookie("UA_usercookie", $cookie_val, time()+(60*60*24*30*12));
			$qpiece = ", cookiepwd = \"".md5($cookie_val)."\" ";
		}
		$query = "UPDATE users SET last_login=\"".time()."\" $qpiece WHERE id=\"$this->id_user\" ";
		$this->db->execute($query);
		
		
	}
	
	/**
	 * Funzione che scrive i log di accesso all'applicazione su file
	 * Il file è definito in ../_inc/configure.php
	 *
	 * @param string $log
	 */
	private function writeLog($log)
	{
		global $ACCESS_LOG;
		file_put_contents($ACCESS_LOG, date('c')."\t".$this->userIP."\t".$log."\t".$_SERVER[HTTP_REFERER]."\n", FILE_APPEND | LOCK_EX);
	}
	
	/**
	 * Controlla esistenza di un Header generato da un eventuale proxy e ritorna IP del client
	 *
	 * @return string
	 */
	
	static function getUserIP()
	{
		if (strlen($_SERVER["HTTP_X_FORWARDED"])>=8) {
			return $_SERVER["HTTP_X_FORWARDED"]."P";
		} elseif (strlen($_SERVER["HTTP_FORWARDED_FOR"])>=8) {
			return $_SERVER["HTTP_FORWARDED_FOR"]."P";
		} elseif (strlen($_SERVER["HTTP_FORWARDED"])>=8) {
			return $_SERVER["HTTP_FORWARDED"]."P";
		} elseif (strlen($_SERVER["HTTP_X_FORWARDED"])>=8) {
			return $_SERVER["HTTP_X_FORWARDED"]."P";
		
		}elseif (strlen($_SERVER["HTTP_VIA"])>=8) {
			return $_SERVER["HTTP_VIA"]."P";
		}elseif (strlen($_SERVER["HTTP_X_FORWARDED_FOR"])>=8) {
			return $_SERVER["HTTP_X_FORWARDED_FOR"]."P";
		}elseif (strlen($_SERVER["HTTP_CLIENT_IP"])>=8) {
			return $_SERVER["HTTP_CLIENT_IP"]."P";
		}elseif (strlen($_SERVER["HTTP_FORWARDED_FOR_IP"])>=8) {
			return $_SERVER["HTTP_FORWARDED_FOR_IP"]."P";
		}elseif (strlen($_SERVER["VIA"])>=8) {
			return $_SERVER["VIA"]."P";
		}elseif (strlen($_SERVER["X_FORWARDED_FOR"])>=8) {
			return $_SERVER["X_FORWARDED_FOR"]."P";
		}elseif (strlen($_SERVER["FORWARDED_FOR"])>=8) {
			return $_SERVER["FORWARDED_FOR"]."P";
		}elseif (strlen($_SERVER["X_FORWARDED"])>=8) {
			return $_SERVER["X_FORWARDED"]."P";
		}elseif (strlen($_SERVER["FORWARDED"])>=8) {
			return $_SERVER["FORWARDED"]."P";
		}elseif (strlen($_SERVER["CLIENT_IP"])>=8) {
			return $_SERVER["CLIENT_IP"]."P";
		}elseif (strlen($_SERVER["FORWARDED_FOR_IP"])>=8) {
			return $_SERVER["FORWARDED_FOR_IP"]."P";
		}elseif (strlen($_SERVER["HTTP_PROXY_CONNECTION"])>=8) {
			return $_SERVER["HTTP_PROXY_CONNECTION"]."P";
		} 
		else {
			return $_SERVER["REMOTE_ADDR"];
		}
	}
	
}
?>